package com.h5lib.nchuoffice;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;

import com.h5lib.nchuoffice.constants.SysConstant;
import com.h5lib.nchuoffice.model.Class_;
import com.h5lib.nchuoffice.model.Course;
import com.h5lib.nchuoffice.model.Grade;
import com.h5lib.nchuoffice.model.Institute;
import com.h5lib.nchuoffice.model.SchoolGrade;
import com.h5lib.nchuoffice.model.SchoolTermGrade;
import com.h5lib.nchuoffice.model.SchoolYearGrade;
import com.h5lib.nchuoffice.model.Term;
import com.h5lib.nchuoffice.model.UserInfo;
import com.h5lib.nchuoffice.model.Year;

/**
 * 
 * @author framer
 *
 */
public class NchuOfficeUtils {
	
	//课程成绩
	public final static String GRADE = "GRADE";
	//学年成绩
	public final static String SCHOOLYEARGRADE = "SCHOOLYEARGRADE";
	//学期成绩
	public final static String SCHOOLTERMGRADE = "SCHOOLTERMGRADE";
	//在校成绩
	public final static String SCHOOLGRADE = "SCHOOLGRADE";
	//学期基础数据
	public final static String TERMS = "TERMS";
	//学院基础数据
	public final static String INSTITUTES = "INSTITUTES";
	//年
	public final static String YEARS = "YEARS";
	/**
	 * 登录接口
	 * @throws IOException 
	 * 
	 */
	public static UserInfo login(String username ,String password) throws IOException{
		//登录校验
		System.out.println("======权限校验操作开始======");
		Response response = Jsoup.connect(SysConstant.JWC_LOGIN_CHECK_URL)
					.header("User-Agent", SysConstant.USER_AGENT)
					.header("Host", SysConstant.HOST)
					.header("Referer", SysConstant.REFERER)
					.header("Content-Type", "application/x-www-form-urlencoded")
					.cookies(Cookies.getCookies())
					.data("username",username)
					.data("password",password)
					.data("role","student")
					.timeout(SysConstant.TIMEOUT)
					.method(Method.GET).execute();
		Cookies.addCookies(response.cookies());
		System.out.println("======权限校验操作完成======");
		Document doc = response.parse();
		Element infoTable = doc.getElementById("InformationPanel");
		if(infoTable == null){
			return null;
		}
		else{
			UserInfo userInfo = new UserInfo();
			userInfo.setUserNo(infoTable.getElementsByTag("span").get(2).text());
			userInfo.setUserName(infoTable.getElementsByTag("span").get(4).text());
			userInfo.setClassNo(infoTable.getElementsByTag("span").get(6).text());
			userInfo.setMajorName(infoTable.getElementsByTag("span").get(8).text());
			return userInfo;
		}
	}
	
	/**
	 * 查询成绩接口
	 * @return
	 * @throws IOException 
	 * @throws NchuSqlException 
	 */
	public static Map<String,Object> getGrades() throws IOException, NchuSqlException{
		String schoolYear = "学年";
		String schoolTerm = "学期";
		Map<String, Object> gradesMap = new HashMap<String, Object>();
		List<Grade> grades = new ArrayList<Grade>();		//单科成绩
		List<SchoolTermGrade> schoolTermGrades = new ArrayList<SchoolTermGrade>();  //学期平均成绩
		List<SchoolYearGrade> schoolYearGrades = new ArrayList<SchoolYearGrade>();	//学年平均成绩
		Response response = Jsoup.connect(SysConstant.JWC_STUDENTGRADE_ACTION_URL)
				.header("User-Agent", SysConstant.USER_AGENT)
				.header("Host", SysConstant.HOST)
				.header("Referer", SysConstant.REFERER)
				.parser(Parser.htmlParser())
				.cookies(Cookies.getCookies())
				.timeout(SysConstant.TIMEOUT)
				.method(Method.GET).execute();
		Document doc = response.parse();
		Elements trs = doc.getElementById("Table1").getElementsByTag("tr");
		System.out.println(trs.toString());
		if(doc.toString().indexOf(SysConstant.SQLEXCEPTION) != -1){
			throw new NchuSqlException("服务器数据库异常");
		}
		for (Element tr : trs) {
			if(tr.hasAttr("bgcolor")){
				continue;	//过滤标题栏
			}
			else{
				Grade grade = new Grade();	//解析成绩
				Elements tds = tr.getElementsByTag("td");
				int i = 0;
				if(tds.size() == 12){	//学年
					SchoolYearGrade schoolYearGrade = new SchoolYearGrade();
					SchoolTermGrade schoolTermGrade = new SchoolTermGrade();
					schoolYear= tds.get(0).text();
					schoolYearGrade.setSchoolYear(schoolYear);
					schoolTermGrade.setSchoolYear(schoolYear);
					schoolYearGrade.setGrade(tds.get(1).text());
					schoolTerm= tds.get(2).text();
					schoolTermGrade.setSchoolTerm(schoolTerm);
					schoolTermGrade.setGrade(tds.get(3).text());
					schoolTermGrades.add(schoolTermGrade);
					schoolYearGrades.add(schoolYearGrade);
					i=i+4;
				}
				if(tds.size() == 10){	//学期
					SchoolTermGrade schoolTermGrade = new SchoolTermGrade();
					schoolTermGrade.setSchoolYear(schoolYear);
					schoolTerm= tds.get(0).text();
					schoolTermGrade.setSchoolTerm(schoolTerm);
					schoolTermGrade.setGrade(tds.get(1).text());
					schoolTermGrades.add(schoolTermGrade);
					i=i+2;
				}
				grade.setCourse(tds.get(i++).text());
				grade.setType(tds.get(i++).text());
				grade.setCredit(tds.get(i++).text());
				grade.setPeriod(tds.get(i++).text());
				grade.setGrade(tds.get(i++).text());
				grade.setCensor(tds.get(i++).text());
				grade.setNature(tds.get(i++).text());
				grade.setSchoolYear(schoolYear);
				grade.setSchoolTerm(schoolTerm);
				grades.add(grade);
			}

		}
		SchoolGrade schoolGrade = new SchoolGrade();
		//总成绩
		try {

			Elements tds = doc.getElementById("Table2").getElementsByTag("tr").get(0).getElementsByTag("td");
			schoolGrade.setGrade(tds.get(1).text());
			schoolGrade.setCredit(tds.get(3).text());
			schoolGrade.setTotal(tds.get(5).text());
			schoolGrade.setPass(tds.get(7).text());
			schoolGrade.setUnpass(tds.get(9).text());
		} catch (Exception e) {
			e.printStackTrace();
		}
		gradesMap.put(GRADE, grades);
		gradesMap.put(SCHOOLTERMGRADE, schoolTermGrades);
		gradesMap.put(SCHOOLYEARGRADE, schoolYearGrades);
		gradesMap.put(SCHOOLGRADE, schoolGrade);
		return gradesMap;
	}
	
	/**
	 * 查询班级课程
	 * @param year
	 * @param institute
	 * @param _class
	 * @param schoolTerm
	 * @return
	 * @throws IOException
	 */
	public static List<Course> getCoursesByClass(String year,String institute,String _class, String schoolTerm) throws IOException{
		//课程
		List<Course> courses = new ArrayList<Course>();
		//模拟进入查询，获取到viewstate
		Response response = Jsoup.connect(SysConstant.QUERY_LESSON_BY_CLASS_URL)
					.header("User-Agent", SysConstant.USER_AGENT)
					.header("Host", SysConstant.HOST)
					.header("Referer", SysConstant.REFERER)
					.data("queryMode","c")
					.cookies(Cookies.getCookies())
					.timeout(SysConstant.TIMEOUT)
					.method(Method.GET).execute();
		String viewstate = response.parse().getElementsByAttributeValue("name", "__VIEWSTATE").attr("value");
		//模拟进入选择院系，学期，获取到viewstate
		response = Jsoup.connect(SysConstant.QUERY_LESSON_BY_CLASS_URL)
				.header("User-Agent", SysConstant.USER_AGENT)
				.header("Host", SysConstant.HOST)
				.header("Referer", SysConstant.REFERER)
				.data("queryMode","c")
				.data("ddlInstitute", institute)
				.data("YearDropDownList", schoolTerm)
				.data("__EVENTTARGET", "ddlInstitute")
				.data("__VIEWSTATE", viewstate)
				.cookies(Cookies.getCookies())
				.timeout(SysConstant.TIMEOUT)
				.method(Method.GET).execute();
		viewstate = response.parse().getElementsByAttributeValue("name", "__VIEWSTATE").attr("value");
		
		//模拟进入选择院系，学期，年份，获取到viewstate
		response = Jsoup.connect(SysConstant.QUERY_LESSON_BY_CLASS_URL)
				.header("User-Agent", SysConstant.USER_AGENT)
				.header("Host", SysConstant.HOST)
				.header("Referer", SysConstant.REFERER)
				.data("queryMode","c")
				.data("ddlInstitute", institute)
				.data("YearDropDownList", schoolTerm)
				.data("ddlYear", year)
				.data("__EVENTTARGET", "ddlYear")
				.data("__VIEWSTATE", viewstate)
				.cookies(Cookies.getCookies())
				.timeout(SysConstant.TIMEOUT)
				.method(Method.GET).execute();
		viewstate = response.parse().getElementsByAttributeValue("name", "__VIEWSTATE").attr("value");
		
		//通过班级+学期查询
		response = Jsoup.connect(SysConstant.QUERY_LESSON_BY_CLASS_URL)
				.header("User-Agent", SysConstant.USER_AGENT)
				.header("Host", SysConstant.HOST)
				.header("Referer", SysConstant.REFERER)
				.data(ConnectDataFactory.createQueryCourseByClassData(_class, schoolTerm ,viewstate))
				.cookies(Cookies.getCookies())
				.timeout(SysConstant.TIMEOUT)
				.method(Method.GET).execute();
		Document doc = response.parse();
		System.out.println(doc);
		//封装更多课表
		String moreCourses = doc.getElementById("LessonInfoTextBox").attr("value");
		Map<String, List<Course>> moreCourseMap = new HashMap<String, List<Course>>();
		if(moreCourses != null){
			//按照节次切割
			String[] moreArrary = moreCourses.split("#");
			//按照
			for (String courseItems : moreArrary) {
				List<Course> more = new ArrayList<Course>();
				int keyIndex = courseItems.indexOf("$");
				String key = courseItems.substring(0,keyIndex);
				courseItems = courseItems.substring(keyIndex+1, courseItems.length());
				moreCourseMap.put(key, more);
				String[] items = courseItems.split("@");
				for (String item : items) {
					String[] tags = item.split("[$]");
					Course course = new Course();
					course.setName(StringUtils.between(tags[0],"%","%"));
					course.setTeacher(StringUtils.between(tags[1],"%","%"));
					course.setClassroom( tags[2]);
					course.setTime(tags[3]);
					course.setClass_(tags[5]);
					more.add(course);
				}
			}
		}
		
		Elements trs = doc.getElementById("Table1").child(0).children();
		List<String> weeks = new ArrayList<String>();
		
		for (int i = 0; i < trs.size(); i++) {
			Element tr = trs.get(i);
			if(i == 0){	//星期行
				for (int j = 1; j < 8; j++) {
					weeks.add(tr.child(j).text());
				}
			}else{
				for (int j = 1; j < 8; j++) {
					Course course = new Course();
					course.setNode(tr.child(0).text());
					course.setName(tr.child(j).getElementsByTag("tr").get(0).text());
					course.setTeacher(tr.child(j).getElementsByTag("tr").get(1).text());
					course.setClassroom(tr.child(j).getElementsByTag("tr").get(2).text());
					course.setTime(tr.child(j).getElementsByTag("tr").get(3).text());
					course.setWeek(weeks.get(j-1));
					course.setClass_(tr.child(j).getElementsByTag("tr").get(4).getElementsByTag("span").attr("title"));
					course.setNumber(StringUtils.between(tr.child(j).getElementsByTag("tr").get(4).text(),"(",")"));
					String key = (i)+""+(j);
					course.setMore(moreCourseMap.get(key));
					courses.add(course);
				}
			}
		}
		
		return courses;
	}
	
	/**
	 * 获取基础数据，学期与学院
	 * @return
	 * @throws IOException 
	 */
	public static Map<String, Object> getBaseData() throws IOException{
		Map<String, Object> baseMap = new HashMap<String, Object>();
		List<Term> terms = new ArrayList<Term>();
		List<Institute> institutes = new ArrayList<Institute>();
		List<Year> years = new ArrayList<Year>();
		Response response = Jsoup.connect(SysConstant.QUERY_LESSON_BY_CLASS_URL)
				.header("User-Agent", SysConstant.USER_AGENT)
				.header("Host", SysConstant.HOST)
				.header("Referer", SysConstant.REFERER)
				.data("queryMode","c")
				.cookies(Cookies.getCookies())
				.timeout(SysConstant.TIMEOUT)
				.method(Method.GET).execute();
		Document parse = response.parse();
		Element termSelect = parse.getElementById("YearDropDownList");
		Elements children = termSelect.children();
		for (Element element : children) {
			Term term = new Term();
			term.setValue(element.attr("value"));
			term.setName(element.text());
			terms.add(term);
		}
		Element instituteSelect = parse.getElementById("ddlInstitute");
		children = instituteSelect.children();
		for (Element element : children) {
			Institute institute = new Institute();
			institute.setValue(element.attr("value"));
			institute.setName(element.text());
			institutes.add(institute);
		}
		
		Element yearSelect = parse.getElementById("ddlYear");
		children = yearSelect.children();
		for (Element element : children) {
			Year year = new Year();
			year.setValue(element.attr("value"));
			year.setName(element.text());
			years.add(year);
		}
		
		baseMap.put(TERMS, terms);
		baseMap.put(INSTITUTES, institutes);
		baseMap.put(YEARS, years);
		return baseMap;
	}
	

	public static List<Class_> getClasses(String year, String institute,String schoolTerm) throws IOException {
		List<Class_> classes = new ArrayList<Class_>();
		
		//模拟进入查询，获取到viewstate
		Response response = Jsoup.connect(SysConstant.QUERY_LESSON_BY_CLASS_URL)
					.header("User-Agent", SysConstant.USER_AGENT)
					.header("Host", SysConstant.HOST)
					.header("Referer", SysConstant.REFERER)
					.data("queryMode","c")
					.cookies(Cookies.getCookies())
					.timeout(SysConstant.TIMEOUT)
					.method(Method.GET).execute();
		Document doc = response.parse();
		String viewstate = doc.getElementsByAttributeValue("name", "__VIEWSTATE").attr("value");
		
		response = Jsoup.connect(SysConstant.QUERY_LESSON_BY_CLASS_URL)
				.header("User-Agent", SysConstant.USER_AGENT)
				.header("Host", SysConstant.HOST)
				.header("Referer", SysConstant.REFERER)
				.data("queryMode","c")
				.data("ddlInstitute", institute)
				.data("YearDropDownList", schoolTerm)
				.data("ddlYear", year)
				.data("__EVENTTARGET", "YearDropDownList")
				.data("__VIEWSTATE", viewstate)
				.cookies(Cookies.getCookies())
				.timeout(SysConstant.TIMEOUT)
				.method(Method.GET).execute();
		doc = response.parse();
		viewstate = doc.getElementsByAttributeValue("name", "__VIEWSTATE").attr("value");
		
		//YearDropDownList
		//模拟进入选择院系，学期，获取到viewstate
		response = Jsoup.connect(SysConstant.QUERY_LESSON_BY_CLASS_URL)
				.header("User-Agent", SysConstant.USER_AGENT)
				.header("Host", SysConstant.HOST)
				.header("Referer", SysConstant.REFERER)
				.data("queryMode","c")
				.data("ddlInstitute", institute)
				.data("YearDropDownList", schoolTerm)
				.data("ddlYear", year)
				.data("__EVENTTARGET", "ddlInstitute")
				.data("__VIEWSTATE", viewstate)
				.cookies(Cookies.getCookies())
				.timeout(SysConstant.TIMEOUT)
				.method(Method.GET).execute();
		viewstate = doc.getElementsByAttributeValue("name", "__VIEWSTATE").attr("value");
		
		//模拟进入选择院系，学期，年份，获取到viewstate
		response = Jsoup.connect(SysConstant.QUERY_LESSON_BY_CLASS_URL)
				.header("User-Agent", SysConstant.USER_AGENT)
				.header("Host", SysConstant.HOST)
				.header("Referer", SysConstant.REFERER)
				.data("queryMode","c")
				.data("ddlInstitute", institute)
				.data("YearDropDownList", schoolTerm)
				.data("ddlYear", year)
				.data("__EVENTTARGET", "ddlYear")
				.data("__VIEWSTATE", viewstate)
				.cookies(Cookies.getCookies())
				.timeout(SysConstant.TIMEOUT)
				.method(Method.GET).execute();
		
		doc = response.parse();
		Element termSelect = doc.getElementById("ddlClass");
		Elements children = termSelect.children();
		for (Element element : children) {
			Class_ class_ = new Class_();
			class_.setValue(element.attr("value"));
			class_.setName(element.text());
			classes.add(class_);
		}
		return classes;
	}
	
	/**
	 * 获取当前学期
	 * @return
	 */
	public static String getCurrentSchoolTerm(){
		Calendar calendar = Calendar.getInstance();
		calendar.setTime( new Date());
		return calendar.get(Calendar.YEAR)+""+(calendar.get(Calendar.MONTH)+1>7?1:2);
	}
}
